<template>
    <div>
        <Tabs 
        type="card" 
        closable 
        v-model="currentTab" 
        @on-tab-remove="removeTab"
        :animated="false" >
            <!-- 合同信息 -->
            <TabPane label="合同信息" :closable="false" :name="'0'">
                <Row>
                    <Col span="24">
                        <!-- <Card dis-hover class="no-border-card"> -->
                            <!-- <p slot="title">
                                合同列表
                            </p> -->

                            <Row :gutter="14" class="yd-padding-b-16">
                                <i-col class="c-ticket__row" span="6">
                                    <span class="c-ticket__label">合同状态</span>
                                    <div class="c-ticket__item">
                                        <Select
                                            v-model="filterData.status"
                                            clearable
                                            placeholder='不限'
                                            class='flex-items'>
                                            <Option value="">全部</Option>
                                            <Option :value="1">合同执行中</Option>
                                            <Option :value="2">合同已到期</Option>
                                            <Option :value="3">已作废</Option>
                                        </Select>
                                    </div>
                                </i-col>
                                <i-col class="c-ticket__row" span="12">
                                    <span class="c-ticket__label">创建日期</span>
                                     <div class="c-ticket__item">
                                        <DatePicker 
                                        style="width:48%"
                                        placeholder="开始时间" 
                                        type="date"
                                        v-model="filterData.beginTime"
                                        @on-change="beginTimeChange"
                                        ></DatePicker>
                                        &nbsp;-&nbsp;
                                        <DatePicker 
                                        style="width:48%"
                                        placeholder="结束时间" 
                                        type="date" 
                                        v-model="filterData.endTime"
                                        @on-change="endTimeChange"
                                        ></DatePicker>
                                     </div>
                                </i-col>
                                <i-col class="c-ticket__row" span="6">
                                    <span class="c-ticket__label">搜索关键字</span>
                                    <div class="c-ticket__item">
                                        <Input v-model="filterData.keyword" placeholder="合同名称" />
                                    </div>
                                    <i-button @click="getRenterList(1)" style="width: 70px;height:38px;" type="primary">搜索</i-button>
                                </i-col>
                                
                            </Row>
                            
                            <Row class="yd-padding-b-16">
                                <Table stripe border ref="selection" :columns="columns" :data="renters" :loading="isLoadig"></Table>
                            </Row>
                            <Row>
                                <Page :total="total" 
                                @on-change="getRenterList"
                                :page-size="size" 
                                :current.sync="currentPage"
                                show-elevator 
                                show-total 
                                style="text-align:center"></Page>
                            </Row>
                        <!-- </Card> -->
                    </Col>
                </Row>                
            </TabPane>

            <!-- 合同详情 -->
            <TabPane 
            v-for="(tab,index) in tabs" 
            :name="''+ tab.id" 
            :key="tab.id + index" 
            :label="tab.name" closable>
                <contractDetail :renterId="tab.id"></contractDetail>
            </TabPane>

        </Tabs>

    </div>

    
</template>

<script>
import { http, api } from '@/libs/http'
import contractDetail from './contractDetail.vue'
import { CountryCodes } from '@/libs/const'
import moment from 'moment'
export default {
  components: {
    contractDetail
  },
  data () {
    return {
      roleId: null,
      ydmanagerLoading: false, // 云丁商务
      client: {}, // 用户
      ydmanager: [], // 云丁商务
      CountryCodes,
      currentTab: '0', // 当前Tab
      tabs: [],
      start_time: '',
      filterData: {}, // 搜索列表
      end_time: '',
      leaseIds: [], // lease_id的数组
      isLoadig: false, // 是否正在发请求
      size: 20, // 分页size
      total: 0, // 分页总数
      currentPage: 1,
      keyword: '',
      searchTypes: [
        {
          value: 1,
          label: '合同执行中'
        },
        {
          value: 2,
          label: '合同已到期'
        },
        {
          value: 3,
          label: '已废除'
        }
      ],
      selectSearchType: 0,
      columns: [
        // {
        //     type: 'selection',
        //     width: 60,
        //     align: 'center'
        // },
        {
          title: '合同名称',
          key: 'name',
          align: 'center'
        },
        {
          title: '客户签约主体',
          key: 'clientBodyName',
          align: 'center'
        },
        {
          title: '我方签约主体',
          key: 'yunDingBodyName',
          align: 'center'
        },
        {
          title: '合同类型/结算方式',
          key: 'paymentTypeName',
          align: 'center',
          render: (h, p) => <span>{`${p.row.typeName}-${p.row.paymentTypeName}`}</span>
        },
        // {
        //     title: '总金额',
        //     key: 'phone',
        //     align: 'center'
        // },
        {
          title: '云丁商务',
          key: 'principalName',
          align: 'center'

        },
        {
          title: '状态',
          key: 'statusName',
          align: 'center'
          // render: (h, params) => {
          //     let result = params.row.lease ? '已入住' : '无';
          //     return h('span', result);
          // }
        },
        {
          title: '合同有效期',
          align: 'center',
          render: (h, p) => {
            let result = p.row.beginDate.split(' ')[0] + '-' + p.row.endDate.split(' ')[0]
            return h('span', result)
          }
        },
        {
          title: '操作',
          key: 'action',
          align: 'center',
          render: (h, params) => {
            let btn = []
            if (this.roleId === 100 || this.roleId === 103) {
              btn =
                            h('div', [
                              h(
                                'Button',
                                {
                                  props: {
                                    type: 'ghost',
                                    size: 'small'
                                  },
                                  // class: {
                                  //     'renter-list-hide': !params.row.lease
                                  // },
                                  style: {
                                    marginRight: '5px',
                                    marginLeft: '0px'
                                  },
                                  on: {
                                    click: () => {
                                      // 打开新标签显示详情
                                      let id = '' + params.row.id
                                      let name = '' + params.row.name
                                      this.toContractDetail(id, name)
                                    }
                                  },
                                  directives: [
                                    {
                                      name: 'pmis',
                                      value: 29
                                    }
                                  ]
                                },
                                '查看'
                              )
                            ])
            } else {
              btn = []
            }
            return btn
          }
        }
      ],
      renters: [] // 列表
    }
  },
  created: function () {
    if (this.$route.query.renter_id) {
      this.toContractDetail(this.$route.query.renter_id, this.$route.query.renter_name)
    }
    if (this.$route.query.input) {
      this.keyword = this.$route.query.input
    }
    this.fetchModels()
    this.getUserInfo()// 列表
  },
  methods: {
    async getYdmanager (query) {
      let res = await http.fetch(this, api.client_managers_list, null, {role_id: 6, keyword: query})
      this.ydmanagerLoading = false
      this.ydmanager = res.map(item => {
        return {
          value: item.id,
          label: item.name
        }
      })
    }, // 云丁商务
    remoteMethodYdmanager (query) {
      this.ydmanagerLoading = true
      this.getYdmanager(query)
    }, // 云丁商务select

    toContractDetail (id, name) {
      id = String(id)

      const flag = this.tabs.some(value => {
        return id === value.id
      })

      if (!flag) {
        this.tabs.push({ id, name })
      }

      this.currentTab = id
    },

    /**
         * 移除tab
         */
    removeTab (name) {
      const pos = this.removeTabDetial(this.tabs, name)
      if (pos) {
        return
      }

      this.removeTabDetial(this.leaseIds, name)
    },

    /**
         * 删除tab具体过程
         * @param {Array} obj
         * @param {String} tabName 关闭的列表名
         * @return {Boolean} true => 表示找到已经删除的tab false => 表示循环完之后依旧没有找到要关闭的tab
         */
    removeTabDetial (arr, tabName) {
      // let { length } = arr;
      for (let i = 0; i < arr.length; i++) {
        const { id } = arr[i]

        if (id === tabName) {
          arr.splice(i, 1)
          return true
        }
      }
      return false
    },

    delRenter (renterId) {
      http.request(this, api.tenant_del, [renterId], null, res => {
        if (res) {
          // 删除成功后刷新
          this.getRenterList(1)
        }
      })
    },

    getRenterList (page) {
      if (this.isLoadig) {
        return
      }
      if (page === 1) {
        this.currentPage = 1
      }

      this.isLoadig = true

      this.filterData.clientId = this.client.clientId
      this.filterData.limit = this.size
      this.filterData.offset = this.size * (page - 1) || 0
      http.request(this, api.contract_list, null, this.filterData, res => {
        if (res) {
          this.renters = res.rows
          this.total = res.count || 0
        }
        this.isLoadig = false
      })
    },
    dateChange ([start_time, end_time]) {
      this.start_time = start_time
      this.end_time = end_time
    },
    async getUserInfo () {
      let res = await http.fetch(this, api.user_info, null, null)
      this.roleId = res.role_id
      this.client = {
        clientId: res.client_id,
        clientName: res.client.name
      }
      this.getRenterList(1)
      sessionStorage.setItem('user', JSON.stringify(res))
    }, // 用户信息
    beginTimeChange (val, date) {
      if (!val) return
      this.filterData.beginTime = moment(this.filterData.beginTime).format('YYYY-MM-DD HH:mm:ss')
    }, // 开始时间
    endTimeChange (val, date) {
      if (!val) return
      this.filterData.endTime = moment(this.filterData.endTime).format('YYYY-MM-DD HH:mm:ss')
    }, // 结束时间
    async fetchModels () {
      let res = await http.fetch(this, api.enum, null, null)
      sessionStorage.setItem('device', JSON.stringify(res))
    } // 设备
  }
}
</script>

<style lang="less" scoped>
.renter-list {
    &-title {
        height: auto;
    }
    &-hide {
        display: none;
    }
    &-info {
        padding: 5px 0;
    }
    &-save-succ {
        padding: 20px 0;
        text-align: center;
    }
    &-save-succ .icon {
        font-size: 60px;
    }
    &-save-succ span {
        font-size: 20px;
    }
}

.ivu-tabs-tabpane {
    > div {
        visibility: visible !important;
    }
}

.yd-padding-b-16 {
    padding-bottom: 16px;
}
.export-link {
    color: #fff;
    text-decoration: none;
}
.export-link:hover {
    color: #fff;
}
.c-ticket {
    &__search {
        margin: 20px 0;
        padding-bottom: 20px;
        background-color: #efeff1;
        border-bottom: 1px solid #ddd;
    }
    &__row {
        display: flex;
        align-items: center;
    }

    &__label {
        margin-right: 5px;
    }

    &__item {
        flex: 1;
    }

}
</style>
